/**
 * 
 */
package cn.com.xf.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.com.xf.common.AbstractBaseController;
import cn.com.xf.common.ConfigUtil;
import cn.com.xf.common.Constants;
import cn.com.xf.common.StringUtil;
import cn.com.xf.domain.TblOaSoft;
import cn.com.xf.domain.TblOaSoftType;
import cn.com.xf.service.NoticeService;
import cn.com.xf.service.SettingService;
import cn.com.xf.service.SoftService;
import cn.com.xf.utils.encode.EncrypTool;
import cn.com.xf.web.PageModel;
import cn.com.xf.web.XFMappingJacksonJsonView;
import cn.com.xf.web.form.SoftForm;
import cn.com.xf.web.security.UserInfo;

/**
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("/soft")
public class SoftController extends AbstractBaseController {
	@Autowired
	private SoftService softService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private SettingService settingService;

	@RequestMapping
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response, SoftForm form) throws Exception {
		ModelAndView mv = new ModelAndView("/soft/index", Constants.FORM_COMMAND_KEY, form);
		form.setTab(Constants.TAB_SOFT);
		// List<TblOaSoftType> list = softService.selectCoreFileTypeList();
		// if (!CollectionUtils.isEmpty(list)) {
		// mv.addObject("defaultTypeId", list.get(0).getTypeId());
		// }
		// mv.addObject("fileTypeList", list);
		return mv;
	}

	@RequestMapping(value = "/softl")
	public ModelAndView soft(HttpServletRequest request, HttpServletResponse response, SoftForm form) throws Exception {
		ModelAndView mv = new ModelAndView("/soft/soft", Constants.FORM_COMMAND_KEY, form);
		form.setTab(Constants.TAB_SOFT);
		List<TblOaSoftType> list = softService.selectCoreFileTypeList();
		if (!CollectionUtils.isEmpty(list)) {
			mv.addObject("defaultTypeId", list.get(0).getTypeId());
		}
		mv.addObject("fileTypeList", list);
		return mv;
	}

	@RequestMapping(value = "/list")
	public ModelAndView soft_list(HttpServletRequest request, HttpServletResponse response, SoftForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/soft/soft_list", Constants.FORM_COMMAND_KEY, form);
		// 1.参数
		String fileType = null;
		if (StringUtils.isNotBlank(form.getTypeId())) {
			fileType = form.getTypeId();
		}
		
		//查询员工所属一级中心站点
		UserInfo user = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String siteId = user.getSiteId();
		String centerId = "";
		if("10000".equals(siteId)){
			centerId = "10000";
		}else{
			centerId = noticeService.selectOfCenter(siteId);
		}
		
		// 2.总记录数
		int count = softService.selectCount(fileType, centerId);
		if (count == 0) {
			return mv;
		}

		// 3.分页信息
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();

		// 4.排序规则
		String orderByField = "PUBLIC_DATE";
		String orderByMode = "desc";
		if (StringUtils.isNotBlank(form.getOrderByField()) && StringUtils.isNotBlank(form.getOrderByMode())) {
			if ("title".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "title";
			}
			if ("asc".equalsIgnoreCase(form.getOrderByMode()) || "desc".equalsIgnoreCase(form.getOrderByMode())) {
				orderByMode = form.getOrderByMode();
			}
		}

		// 5.查询
		List<TblOaSoft> list = softService.select(begin, pageSize, orderByField, orderByMode, fileType, centerId);
		if(fileType!=null&&fileType.equals("18")){
			mv.addObject("isBJ","1");
		}
		mv.addObject("list", list);

		return mv;
	}

	/**
	 * 添加记录
	 */
	@RequestMapping(value = "/add")
	public ModelAndView notice_add(HttpServletRequest request, HttpServletResponse response, SoftForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/soft/soft_add", Constants.FORM_COMMAND_KEY, form);
		form.setTab(Constants.TAB_SOFT);
		List<TblOaSoftType> list = softService.selectCoreFileTypeList();
		
		//判断是否是总部账号
		//查询员工所属一级中心站点
		UserInfo user = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String siteId = user.getSiteId();
		String isCenter = "";
		if("10000".equals(siteId)){
			isCenter = "1";
		}else{
			String centerId = noticeService.selectOfCenter(siteId);
			if("769000".equals(centerId)){
				isCenter = "1";
			}
		}
		mv.addObject("isCenter", isCenter);
		mv.addObject("fileTypeList", list);
		return mv;
	}

	/**
	 * 添加文件完成上传文件旧版
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/doAdd2")
	public ModelAndView notice_doAdd2(HttpServletRequest request, HttpServletResponse response, @Valid SoftForm form,
			BindingResult result) throws Exception {
		MultipartFile file = form.getMultipartFile();
		ModelAndView mv = new ModelAndView("/soft/soft_add_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			// 将错误信息Json化
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		//查询员工所属一级中心站点
		UserInfo user = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String siteId = user.getSiteId();
		String centerId = "";
		if("10000".equals(siteId)){
			centerId = "10000";
		}else{
			centerId = noticeService.selectOfCenter(siteId);
		}
		
		if (!file.isEmpty()) {

			// 存储到文件
			String prepath = servletContext.getRealPath("/");
			String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "_"
					+ file.getOriginalFilename();
			String savePath = prepath + Constants.UPLOAD_PATH_FILE;
			String relativePath = Constants.UPLOAD_PATH_FILE + "/" + newFileName;
			File saveFile = new File(savePath, newFileName);
			file.transferTo(saveFile);
			TblOaSoft coreFile = form.copyTo();
			TblOaSoftType type = softService.selectCoreFileTypeById(coreFile.getTypeId());
			coreFile.setFileType(type.getFileType());
			coreFile.setDownfileName(relativePath);
			softService.insert(coreFile,centerId);
			mv.addObject("status", "success");
			return mv;
		}
		mv.addObject("status", "error");
		mv.addObject("msg", "文件不能为空!");
		return mv;
	}

	/**
	 * 新增软件执行
	 * 
	 * @param request
	 * @param response
	 * @param form
	 * @param result
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/doAdd")
	public ModelAndView notice_doAdd(HttpServletRequest request, HttpServletResponse response, @Valid SoftForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/soft/soft_add_result", Constants.FORM_COMMAND_KEY, form);
		// 1.错误检查
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			// 将错误信息Json化
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}

		//查询员工所属一级中心站点
		UserInfo user = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String siteId = user.getSiteId();
		String centerId = "";
		if("10000".equals(siteId)){
			centerId = "10000";
		}else{
			centerId = noticeService.selectOfCenter(siteId);
		}
		
		// 2.提取临时文件中的文件
		// 2.1空值检查
		String tempFileId = form.getTempFileId();
		if (StringUtils.isBlank(form.getTempFileId())) {
			return null;
		}
		// 2.2获取临时文件列表
		String formalFileName = "";
		BigDecimal formalFileSize = null;
		String tempFilesPath = servletContext.getRealPath("/") + Constants.UPLOAD_PATH_TEMP;
		File dir = new File(tempFilesPath);
		File file[] = dir.listFiles();
		// 2.3转存到正式的目录
		for (File f : file) {
			if (f.isFile()) {
				String allname = f.getName();
				if (allname.contains(Constants.UPLOAD_TEMP_SPILT)) {
					String name = allname.split(Constants.UPLOAD_TEMP_SPILT)[0];
					if (tempFileId.equalsIgnoreCase(name)) {
						// 找打了临时文件存储到正式目录
						// String formalFilePath =
						// servletContext.getRealPath("/") +
						// Constants.UPLOAD_PATH_FILE;
						formalFileName = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "_"
								+ allname.split(Constants.UPLOAD_TEMP_SPILT)[1];
						// File formalFile = new File(formalFilePath,
						// formalFileName);
						// 获取文件大小，小数点后两位
						float size = Float.valueOf(f.length()) / 1024.0f / 1024.0f;
						BigDecimal b = new BigDecimal(size);
						size = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
						formalFileSize = new BigDecimal(size + "");
						// 拷贝文件到正式目录
						// fileChannelCopy(f, formalFile);

						// 拷贝文件到绝对地址目录
						String absoluteFilePath = ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME) + File.separator
								+ Constants.ABSOLUTE_ROOT_FILE_PATH;
						File fileFile = new File(absoluteFilePath);
						if (!fileFile.exists()) {
							fileFile.mkdirs();
						}
						File absoluteFile = new File(absoluteFilePath, formalFileName);
						fileChannelCopy(f, absoluteFile);
					}
				}
			}
		}
		if (StringUtils.isBlank(formalFileName)) {
			return null;
		}
		// 3.存储
		TblOaSoft coreFile = form.copyTo();
		TblOaSoftType type = softService.selectCoreFileTypeById(coreFile.getTypeId());
		coreFile.setFileType(type.getFileType());
		coreFile.setDownfileName(formalFileName);
		coreFile.setFileSize(formalFileSize);
		int res = softService.insert(coreFile,centerId);
		if(res==-1){
			mv.addObject("status", "failed");
			mv.addObject("msg", "请选择可见区域");
			return mv;
		}
		mv.addObject("status", "success");
		return mv;
	}

	@RequestMapping(value = "/manageSoftList")
	public ModelAndView manage_soft_list(HttpServletRequest request, HttpServletResponse response, SoftForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/soft/soft_manage_list", Constants.FORM_COMMAND_KEY, form);
		List<TblOaSoftType> listType = softService.selectCoreFileTypeList();
		mv.addObject("fileTypeList", listType);
		String publicMan = StringUtil.StringFilter(form.getPublicMan());
		String createDateBegin = form.getCreateDateBegin();
		String createDateEnd = form.getCreateDateEnd();
		String fileType = StringUtil.StringFilter(form.getTypeId());
		String fileName = StringUtil.StringFilter(form.getName());

		form.setCreateDateBegin(createDateBegin);
		form.setCreateDateEnd(createDateEnd);
		form.setPublicMan(publicMan);
		form.setName(fileName);
		form.setTypeId(fileType);
		// 1.参数
		if (!StringUtils.isNotBlank(form.getTypeId())) {
			fileType = null;
		}
		//1.1是否是总部员工（与浙江系统区分开）
		UserInfo user = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String siteId = user.getSiteId();
		String centerId = "";
		if("10000".equals(siteId)){
			centerId = "10000";
		}else{
			centerId = noticeService.selectOfCenter(siteId);
		}
		
		// 2.总记录数
		int count = softService.selectCount(fileType, fileName, publicMan, createDateBegin, createDateEnd, centerId);
		if (count == 0) {
			return mv;
		}
		// 3.分页信息
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();

		// 4.排序规则
		String orderByField = "PUBLIC_DATE";
		String orderByMode = "desc";
		if (StringUtils.isNotBlank(form.getOrderByField()) && StringUtils.isNotBlank(form.getOrderByMode())) {
			if ("title".equalsIgnoreCase(form.getOrderByField())) {
				orderByField = "title";
			}
			if ("asc".equalsIgnoreCase(form.getOrderByMode()) || "desc".equalsIgnoreCase(form.getOrderByMode())) {
				orderByMode = form.getOrderByMode();
			}
		}

		// 5.查询
		List<TblOaSoft> list = softService.select(begin, pageSize, orderByField, orderByMode, fileType, fileName,
				publicMan, createDateBegin, createDateEnd, centerId);
		mv.addObject("list", list);
		return mv;
	}

	@RequestMapping(value = "/doDelete")
	public ModelAndView doDelete(HttpServletRequest request, HttpServletResponse response, SoftForm form)
			throws Exception {
		String id = form.getId();
		String realId = "";
		if (StringUtils.isNotBlank(id)) {
			realId = EncrypTool.dencode(id);
		}
		int result = softService.deleteById(Integer.valueOf(realId));
		Map map = new HashMap<String, String>();
		if (result < 0) {
			map.put("status", "FAILD");
		} else if (result >= 0) {
			map.put("status", "SUCCESS");
		}
		ModelAndView mv = new ModelAndView(new XFMappingJacksonJsonView(), map);
		return mv;
	}

	@RequestMapping(value = "/edit")
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response, SoftForm form) throws Exception {
		ModelAndView mv = new ModelAndView("/soft/soft_edit", Constants.FORM_COMMAND_KEY, form);
		String id = EncrypTool.dencode(form.getId());
		TblOaSoft soft = softService.selectById(Integer.valueOf(id));
		//判断是否是报价表
		String isBJ = "";
		BigDecimal typeId = BigDecimal.valueOf(18);
		if (0==typeId.compareTo(soft.getTypeId())){
			isBJ = "1";
			String isCenter = "";
			String isZBSoft = "";
			String isZJSoft = "";
			String isFJSoft = "";
			//判断是否是总部账号
			UserInfo user = (UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			String siteId = user.getSiteId();
			if("10000".equals(siteId)){
				isCenter = "1";
			}else{
				String centerId = noticeService.selectOfCenter(siteId);
				if("769000".equals(centerId)){
					isCenter = "1";
				}
			}
			//判断报价表是浙江可见还是总部可见
			List<String> regions = softService.selectRegions(Integer.valueOf(id));
			for(String centerSite:regions){
				if("570000".equals(centerSite)){
					isZJSoft = "1";
				}else if("769000".equals(centerSite)){
					isZBSoft = "1";
				}else if("591000".equals(centerSite)){
					isFJSoft = "1";
				}else if("571002".equals(centerSite)){
					isZBSoft = "1";
				}
			}
			mv.addObject("isCenter", isCenter);
			mv.addObject("isZBSoft", isZBSoft);
			mv.addObject("isZJSoft", isZJSoft);
			mv.addObject("isFJSoft", isFJSoft);
		}
		mv.addObject("isBJ", isBJ);
		
		List<TblOaSoftType> listType = softService.selectCoreFileTypeList();
		mv.addObject("fileTypeList", listType);
		mv.addObject("soft", soft);
		return mv;
	}

	@RequestMapping(value = "/doEdit")
	public ModelAndView doEdit(HttpServletRequest request, HttpServletResponse response, @Valid SoftForm form,
			BindingResult result) throws Exception {
		/*
		 * ModelAndView mv = new ModelAndView("/soft/soft_edit_result",
		 * Constants.FORM_COMMAND_KEY, form); MultipartFile file =
		 * form.getMultipartFile(); String id =
		 * EncrypTool.dencode(form.getId()); TblOaSoft coreFile = form.copyTo();
		 * coreFile.setFileId(Integer.valueOf(id)); TblOaSoftType type =
		 * softService.selectCoreFileTypeById(coreFile.getTypeId());
		 * coreFile.setFileType(type.getFileType()); UserInfo user = (UserInfo)
		 * SecurityContextHolder
		 * .getContext().getAuthentication().getPrincipal();
		 * coreFile.setUpdateTime(new Date()); // 设置更新时间
		 * coreFile.setUpdateUser(user.getName()); // 设置更新人 List<ObjectError>
		 * errorList = null; if (result.hasErrors()) { errorList =
		 * result.getAllErrors(); // 将错误信息Json化 String errorJson =
		 * errorToJson(errorList); mv.addObject("errorJson", errorJson); return
		 * mv; } if (file.isEmpty()) { TblOaSoft soft =
		 * softService.selectById(coreFile.getFileId());
		 * coreFile.setDownfileName(soft.getDownfileName());
		 * softService.update(coreFile); mv.addObject("status", "success");
		 * return mv; } String prepath = servletContext.getRealPath("/"); String
		 * newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new
		 * Date()) + "_" + file.getOriginalFilename(); String savePath = prepath
		 * + Constants.UPLOAD_PATH_FILE; String relativePath =
		 * Constants.UPLOAD_PATH_FILE + "/" + newFileName; File saveFile = new
		 * File(savePath, newFileName); file.transferTo(saveFile);
		 * coreFile.setDownfileName(relativePath); softService.update(coreFile);
		 * mv.addObject("status", "success");
		 * 
		 * return mv;
		 */

		ModelAndView mv = new ModelAndView("/soft/soft_edit_result", Constants.FORM_COMMAND_KEY, form);
		// 1.错误检查
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			// 将错误信息Json化
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		String fileId = EncrypTool.dencode(form.getId() + "");
		TblOaSoft soft = softService.selectById(Integer.valueOf(fileId));
		if (null == soft) {
			return null;
		}
		// 2.提取临时文件中的文件
		// 2.1空值检查
		String tempFileId = form.getTempFileId();
		// 软件没有修改，直接保存其他字段
		if (StringUtils.isNotBlank(form.getTempFileId())) {
			// 2.2获取临时文件列表
			String formalFileName = "";
			BigDecimal formalFileSize = null;
			String tempFilesPath = servletContext.getRealPath("/") + Constants.UPLOAD_PATH_TEMP;
			File dir = new File(tempFilesPath);
			File file[] = dir.listFiles();
			// 2.3转存到正式的目录
			for (File f : file) {
				if (f.isFile()) {
					String allname = f.getName();
					if (allname.contains(Constants.UPLOAD_TEMP_SPILT)) {
						String name = allname.split(Constants.UPLOAD_TEMP_SPILT)[0];
						if (tempFileId.equalsIgnoreCase(name)) {
							// 找打了临时文件存储到正式目录
							String formalFilePath = servletContext.getRealPath("/") + Constants.UPLOAD_PATH_FILE;
							formalFileName = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "_"
									+ allname.split(Constants.UPLOAD_TEMP_SPILT)[1];
							// File formalFile = new File(formalFilePath,
							// formalFileName);
							// 获取文件大小，小数点后两位
							float size = Float.valueOf(f.length()) / 1024.0f / 1024.0f;
							BigDecimal b = new BigDecimal(size);
							size = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
							formalFileSize = new BigDecimal(size + "");
							// 拷贝文件到正式目录
							// fileChannelCopy(f, formalFile);

							// 拷贝文件到绝对地址目录
							String absoluteFilePath = ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME)
									+ File.separator + Constants.ABSOLUTE_ROOT_FILE_PATH;
							File fileFile = new File(absoluteFilePath);
							if (!fileFile.exists()) {
								fileFile.mkdirs();
							}
							File absoluteFile = new File(absoluteFilePath, formalFileName);
							fileChannelCopy(f, absoluteFile);
						}
					}
				}
			}
			if (StringUtils.isBlank(formalFileName)) {
				return null;
			}
			soft.setDownfileName(formalFileName);
			soft.setFileSize(formalFileSize);
		}

		// 3.存储
		soft.setFileName(form.getName());
		soft.setFileDesc(form.getDesc());
		soft.setPublicMan(form.getPublicMan());
		soft.setTypeId(BigDecimal.valueOf(Long.valueOf(form.getTypeId())));
		soft.setPublicDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(form.getPublicDate()));
		soft.setDateStr(form.getPublicDate());
		soft.setUpdateTime(new Date());
		UserInfo user = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		soft.setUpdateUser(user.getName());
		soft.setToZB(form.getToZB());
		soft.setToZJ(form.getToZJ());
		soft.setToFJ(form.getToFJ());
		int res = softService.update(soft);
		if(res==-1){
			mv.addObject("msg", "请选择可见区域");
			mv.addObject("status", "failed");
			return mv;
		}
		mv.addObject("status", "success");
		return mv;
	}

	/**
	 * 
	 * @param s源文件
	 * @param t目标文件
	 */
	private void fileChannelCopy(File s, File t) {
		FileInputStream fi = null;
		FileOutputStream fo = null;
		FileChannel in = null;
		FileChannel out = null;
		try {
			fi = new FileInputStream(s);
			fo = new FileOutputStream(t);
			in = fi.getChannel();// 得到对应的文件通道
			out = fo.getChannel();// 得到对应的文件通道
			in.transferTo(0, in.size(), out);// 连接两个通道，并且从in通道读取，然后写入out通道
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fi.close();
				in.close();
				fo.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
